/*
 * Copyright (c) 2018. 玺得（深圳）科技有限公司.保留所有权利. http://www.pi-top.com/ 玺得（深圳）科技有限公司保留所有代码著作权.如有任何疑问请访问官方网站与我们联系. 代码只针对特定需求定制编码，不得在未经允许或授权的情况下对外传播扩散.恶意传播者，法律后果自行承担. 本代码仅用于pps-cloud系统.
 */
package com.pitop.staff.ctrl;


import com.alibaba.fastjson.JSON;
import com.pitop.core.entity.BeanRet;
import com.pitop.core.entity.Page;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.tools.RegExpUtils;
import com.pitop.core.tools.UuidTools;
import com.pitop.core.tools.redis.RedisUtils;
import com.pitop.staff.entity.Staff;
import com.pitop.staff.entity.StaffVO;
import com.pitop.staff.service.StaffSVImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 员工信息 控制器
 *
 * @author pi-top
 */
@RestController
@RequestMapping("/staff")
@Slf4j
@Api(value = "员工信息控制器", description = "员工信息控制器")
public class StaffCtrl {

    @Resource
    protected RedisUtils redisUtils;
    @Autowired
    private StaffSVImpl staffSVImpl;


    /**
     * 查询Staff一个详情信息
     *
     * @param id
     * @param code 唯一编码
     * @return BeanRet
     */
    @ApiOperation(value = "查询Staff一个详情信息", notes = "查询Staff一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", dataType = "java.lang.Long", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "唯一编码", dataType = "java.lang.String", paramType = "query")
    })
    @GetMapping(value = "/load")
    @ResponseBody
    public BeanRet load(java.lang.Long id, java.lang.String code) {
        if (id == null) {
            return null;
        }
        if (code == null) {
            return null;
        }
        Staff staff = staffSVImpl.load(id, code);
        log.info(JSON.toJSONString(staff));
        return BeanRet.create(true, BaseException.BaseExceptionEnum.Success, staff.toStaffVO());
    }


    /**
     * 根据条件id查询Staff一个详情信息
     *
     * @param id
     * @return BeanRet
     */
    @ApiOperation(value = "查询Staff一个详情信息", notes = "查询Staff一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", dataType = "java.lang.Long", paramType = "path")
    })
    @GetMapping(value = "/load/id/{id}")
    @ResponseBody
    public BeanRet loadById(@PathVariable java.lang.Long id) {
        if (id == null || id == 0) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        Staff staff = staffSVImpl.loadById(id);
        log.info(JSON.toJSONString(staff));
        return BeanRet.create(true, BaseException.BaseExceptionEnum.Success, staff.toStaffVO());
    }

    /**
     * 根据条件code查询Staff一个详情信息
     *
     * @param code 唯一编码
     * @return BeanRet
     */
    @ApiOperation(value = "查询Staff一个详情信息", notes = "查询Staff一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "唯一编码", dataType = "java.lang.String", paramType = "path")
    })
    @GetMapping(value = "/load/code/{code}")
    @ResponseBody
    public BeanRet loadByCode(@PathVariable java.lang.String code) {
        if (StringUtils.isEmpty(code)) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        Staff staff = staffSVImpl.loadByCode(code);
        log.info(JSON.toJSONString(staff));
        return BeanRet.create(true, BaseException.BaseExceptionEnum.Success, staff.toStaffVO());
    }


    /**
     * 查询Staff信息集合
     *
     * @return 分页对象
     */
    @ApiOperation(value = "查询Staff信息集合", notes = "查询Staff信息集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "curPage", value = "当前页", required = true, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", required = true, paramType = "query"),
            @ApiImplicitParam(name = "id", value = "", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "唯一编码", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "姓名", paramType = "query"),
            @ApiImplicitParam(name = "jobnumber", value = "工号", paramType = "query"),
            @ApiImplicitParam(name = "factoryCode", value = "工厂编码", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "电话", paramType = "query"),
            @ApiImplicitParam(name = "gender", value = "性别", paramType = "query"),
            @ApiImplicitParam(name = "address", value = "地址", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态 入职 hire，离职 leave", paramType = "query"),
            @ApiImplicitParam(name = "hiredate", value = "入职时间", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "创建时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间", paramType = "query"),
            @ApiImplicitParam(name = "ver", value = "版本", paramType = "query")
    })
    @GetMapping(value = "/list")
    @ResponseBody
    public BeanRet list(@ApiIgnore Staff staff, @ApiIgnore Page<StaffVO> page) {
        if (page == null) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        List<Staff> staffs = staffSVImpl.list(staff, page.getCurPage(), page.getPageSize());
        int total = staffSVImpl.count(staff);
        page.setTotalRow(total);
        page.setVoList(Staff.toStaffVOList(staffs));
        log.info(JSON.toJSONString(page));
        return BeanRet.create(true, BaseException.BaseExceptionEnum.Success, "", page);
    }


    /**
     * 查询Staff信息集合
     *
     * @return 分页对象
     */
    @ApiOperation(value = "查询Staff信息集合", notes = "查询Staff信息集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "curPage", value = "当前页", required = true, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", required = true, paramType = "query"),
            @ApiImplicitParam(name = "id", value = "", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "唯一编码", paramType = "query")
    })
    @GetMapping(value = "/list/by")
    @ResponseBody
    public BeanRet listByPk(java.lang.Long id, java.lang.String code, @ApiIgnore Page<StaffVO> page) {
        if (page == null) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        List<Staff> staffs = staffSVImpl.list(id, code, page.genRowStart(), page.getPageSize());
        int total = staffSVImpl.count(id, code);
        page.setTotalRow(total);
        page.setVoList(Staff.toStaffVOList(staffs));
        log.info(JSON.toJSONString(page));
        return BeanRet.create(true, BaseException.BaseExceptionEnum.Success, "", page);
    }

    /**
     * 创建Staff
     *
     * @return BeanRet
     */
    @ApiOperation(value = "创建Staff", notes = "创建Staff")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", paramType = "query"),
            @ApiImplicitParam(name = "factoryCode", value = "工厂编码", required = true, paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "电话", paramType = "query"),
            @ApiImplicitParam(name = "gender", value = "性别", paramType = "query"),
            @ApiImplicitParam(name = "address", value = "地址", paramType = "query"),
            @ApiImplicitParam(name = "hiredate", value = "入职时间", paramType = "query"),
            @ApiImplicitParam(name = "ver", value = "版本", paramType = "query")
    })
    @PostMapping("/build")
    @ResponseBody
    public BeanRet build(@ApiIgnore Staff staff) {
        Staff phoneStaff = new Staff();
        if (StringUtils.isEmpty(staff.getName())) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringUtils.isEmpty(staff.getPhone())) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringUtils.isEmpty(staff.getGender())) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringUtils.isEmpty(staff.getAddress())) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringUtils.isEmpty(staff.getFactoryCode())) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (staff.getHiredate() == null) {
            staff.setHiredate(new Date());
        }

        if (!RegExpUtils.checkPhone(staff.getPhone())) {
            return BeanRet.create(BaseException.BaseExceptionEnum.phone_Incorrect);
        }
        phoneStaff.setPhone(staff.getPhone());
        List<Staff> phoneStaffs = staffSVImpl.list(phoneStaff, 1, 10);
        if (phoneStaffs != null && !phoneStaffs.isEmpty()) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Exists);
        }
        //获取已有的jobNumber,自动生成对应的JobNumber
        Staff jobNumberStaff = new Staff();
        jobNumberStaff.setFactoryCode(staff.getFactoryCode());
        List<Staff> jobNumberStaffs = staffSVImpl.list(jobNumberStaff, 1, 1000);
        if (jobNumberStaffs != null && !jobNumberStaffs.isEmpty()) {
            String jobNumber = null;
            for (Staff staffTemp : jobNumberStaffs) {
                jobNumber = UuidTools.getJobNumber(staffTemp.getJobnumber());
                if (StringUtils.isBlank(jobNumber)) {
                    return BeanRet.create(false, BaseException.BaseExceptionEnum.JobNumber_Illegal, staffTemp.getJobnumber());
                }
                Staff staffByJobNumber = staffSVImpl.loadStaffByJobNumberAndFactoryCode(jobNumber, staff.getFactoryCode());
                if (staffByJobNumber == null) {
                    staff.setJobnumber(jobNumber);
                    break;
                }
            }
            if (StringUtils.isBlank(jobNumber)) {
                return BeanRet.create(false, BaseException.BaseExceptionEnum.JobNumber_Illegal);
            }
        } else {
            staff.setJobnumber("001");
        }
        staffSVImpl.save(staff);
        return BeanRet.create(true, BaseException.BaseExceptionEnum.Success, staff.toStaffVO());
    }


    /**
     * 修改Staff
     *
     * @return BeanRet
     */
    @ApiOperation(value = "修改Staff", notes = "修改Staff")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "唯一编码", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "姓名", paramType = "query"),
            @ApiImplicitParam(name = "jobnumber", value = "工号", paramType = "query"),
            @ApiImplicitParam(name = "factoryCode", value = "工厂编码", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "电话", paramType = "query"),
            @ApiImplicitParam(name = "gender", value = "性别", paramType = "query"),
            @ApiImplicitParam(name = "address", value = "地址", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态 入职 hire，离职 leave", paramType = "query"),
            @ApiImplicitParam(name = "hiredate", value = "入职时间", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "创建时间", paramType = "query"),
            @ApiImplicitParam(name = "updateTime", value = "更新时间", paramType = "query"),
            @ApiImplicitParam(name = "ver", value = "版本", paramType = "query")
    })
    @PutMapping("/modify")
    @ResponseBody
    public BeanRet modify(@ApiIgnore Staff staff) {
        if (StringUtils.isEmpty(staff.getCode())) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringUtils.isEmpty(staff.getName())) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringUtils.isEmpty(staff.getJobnumber())) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringUtils.isEmpty(staff.getPhone())) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringUtils.isEmpty(staff.getGender())) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringUtils.isEmpty(staff.getAddress())) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringUtils.isEmpty(staff.getState())) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        if (StringUtils.isEmpty(staff.getFactoryCode())) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }
        Staff oldStaff = staffSVImpl.loadByCode(staff.getCode());
        if (oldStaff == null) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Result_Not_Exist);
        }
        if (!oldStaff.getJobnumber().equals(staff.getJobnumber())) {
            Staff staffJobNumber = staffSVImpl.loadStaffByJobNumber(staff.getJobnumber());
            if (staffJobNumber != null) {
                return BeanRet.create(BaseException.BaseExceptionEnum.JobNumber_Exist);
            }
        }
        if (StringUtils.isNotBlank(staff.getPhone()) && !oldStaff.getPhone().equals(staff.getPhone())) {
            if (!RegExpUtils.checkPhone(staff.getPhone())) {
                //表示手机好格式不正确
                return BeanRet.create(BaseException.BaseExceptionEnum.phone_Incorrect);
            }
            Staff phoneStaff = new Staff();
            phoneStaff.setPhone(staff.getPhone());
            List<Staff> phoneStaffs = staffSVImpl.list(phoneStaff, 1, 10);
            if (phoneStaffs != null && phoneStaffs.size() > 0) {
                return BeanRet.create(BaseException.BaseExceptionEnum.Exists);
            }
        }
        staffSVImpl.modify(staff);
        return BeanRet.create(true, BaseException.BaseExceptionEnum.Success, staff.toStaffVO());
    }

    /**
     * 根据主键删除Staff
     *
     * @return BeanRet
     */
    @ApiOperation(value = "删除Staff", notes = "删除Staff")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "唯一编码", paramType = "query")
    })
    @DeleteMapping("/delete")
    @ResponseBody
    public BeanRet delete(java.lang.Long id, java.lang.String code) {
        if (id != null && StringUtils.isEmpty(code)) {
            return BeanRet.create(BaseException.BaseExceptionEnum.Empty_Param);
        }

        staffSVImpl.delete(id, code);
        return BeanRet.create(true, "删除Staff成功");
    }

    @ApiOperation(value = "根据员工号和姓名模糊查询", notes = "根据员工号和姓名模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jobNumber", value = "jobNumber", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "name", paramType = "query"),
            @ApiImplicitParam(name = "factoryCode", value = "factoryCode", paramType = "query"),
            @ApiImplicitParam(name = "curPage", value = "当前页", required = true, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", required = true, paramType = "query")
    })
    @RequestMapping(value = "/listByJobNumberAndNameAndFactoryCode", method = RequestMethod.GET)
    @ResponseBody
    public BeanRet listByJobNumberAndNameAndFactoryCode(String jobNumber, String name, String factoryCode, @ApiIgnore Page<StaffVO> page) {
        List<Staff> staffList = staffSVImpl.listByJobNumberAndNameAndFactoryCode(jobNumber, name, factoryCode, page.getCurPage(), page.getPageSize());
        int total = staffSVImpl.countByJobNumberAndNameAndFactroyCode(jobNumber, name, factoryCode);
        page.setTotalRow(total);
        page.setVoList(Staff.toStaffVOList(staffList));
        return BeanRet.create(true, BaseException.BaseExceptionEnum.Success, "", page);
    }


}
